import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:untitled/models/user_info.dart';
import 'package:untitled/utils/store.dart';
import 'package:untitled/utils/string_is_null_or_empty.dart';

import '../utils/dio_http.dart';

class AuthModel extends Model{
  String _token = '';
  UserInfo _userInfo;
  //获取token
  String get token =>_token;
  UserInfo get userInfo =>_userInfo;
  //判断是否已登录
  bool get isLogin => _token is String && _token != '';

  void initApp(BuildContext context) async{
    Store store = await Store.getInstance();
    String token = await store.getString(StoreKeys.token);
    if(!stringIsNullOrEmpty(token)){
      login(token,context);
    }
  }

  _getUserInfo(BuildContext context) async{
    const url = '/user';
    var res = await DioHttp.of(context).get(url,null,_token);
    var resMap = json.decode(res.toString());
    var data = resMap['body'];
    var userInfo = UserInfo.formJson(data);
    _userInfo = _userInfo;
    notifyListeners();
  }

  void login(String token,BuildContext context){
    _token = token;
    notifyListeners();//通知数据改变
    _getUserInfo(context);
  }

  void logout(){
    _token = '';
    _userInfo = null;
    notifyListeners();
  }


}